import { Upload, Icon, Modal, message } from 'antd';
import { config } from '../utils'
const { api, optionalUrl } = config;

class Avatar extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            previewVisible: false,
            previewImage: '',
            fileList:[],
            file:[],
    };
    }

    handleCancel = () => this.setState({ previewVisible: false })

    handlePreview = (file) => {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
        });
    }

    handleChange = (info) =>{
        const {file,fileList} = info;
        const status = file.status;
        if(fileList.length > 0){
            if(status === 'done'){
                if(info.file.response.code == '200'){
                    const img = info.file.response.data;
                    message.success(info.file.response.msg);
                    this.props.onChange(img);
                }else{
                    message.error(info.file.response.msg)
                    return;
                }
            }
        }else{
            this.props.onChange('');
        }
        
        this.setState({fileList,file})
    } 

    render() {
        const {imgPhoto} = this.props;
        const { previewVisible, previewImage,file} = this.state;
        const fileList = imgPhoto&& file.length == 0 ? [{
            uid: '-1',
            name:'xxx.png',
            status:'done',
            url:''
        }] : this.state.fileList;
        const uploadButton = (
            <div>
                <Icon type="plus" />
                <div className="ant-upload-text">{this.props.avatarName}</div>
            </div>
        );
        return (
            <div className="clearfix">
                <Upload
                    action={api.uploadPic}
                    listType="picture-card"
                    fileList={fileList}
                    onPreview={this.handlePreview}
                    onChange={this.handleChange}
                >
                    {fileList.length > 0 ? null : uploadButton}
                </Upload>
                <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </div>
        );
    }
}

export default Avatar